﻿namespace LP
{
    using System;
    using System.Collections.Generic;

    public abstract class AbsModelMgr : AbsMgr, IClear
    {
        private Dictionary<Type, AbsModel> cacheModels = new Dictionary<Type, AbsModel>();

        public override void OnInit()
        {
            base.OnInit();
            IsUpdate = false;
            RegModels();
        }

        public abstract void RegModels();

        public T RegModel<T>() where T : AbsModel
        {
            Type type = typeof(T);
            T model = default;
            if (!cacheModels.ContainsKey(type))
            {
                model = Activator.CreateInstance<T>();
                model.OnInit();
                cacheModels.Add(type, model);
            }
            return model;
        }

        public void UnRegModel<T>() where T : AbsModel
        {
            Type type = typeof(T);
            if (cacheModels.TryGetValue(type, out var model))
            {
                model.OnDestroy();
                cacheModels.Remove(type);
            }
        }

        public T RetriveModel<T>() where T : AbsModel
        {
            Type type = typeof(T);
            AbsModel model = default;
            cacheModels.TryGetValue(type, out model);
            return model as T;
        }

        public override void OnDestroy()
        {
            foreach (var item in cacheModels.Values)
            {
                item.OnDestroy();
            }
            cacheModels.Clear();
            base.OnDestroy();
        }

        public override void OnInitFinish()
        {
            base.OnInitFinish();
            foreach (var item in cacheModels.Values)
            {
                item.OnInitFinish();
            }
        }

        public virtual void OnClear()
        {
            foreach (var item in cacheModels.Values)
            {
                item.OnClear();
            }
        }
    }
}
